﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Xenta;
using Xenta.Utils;

namespace IisHost.UI
{
    public partial class PluginControl : UserControl
    {
        public string Infrastructure
        {
            get
            {
                return ViewState["Infrastructure"] as String;
            }
            set
            {
                ViewState["Infrastructure"] = value;
            }
        }

        private string FilePath
        {
            get
            {
                return Path.Combine(HostingEnvironment.MapPath("~/App_Data"), 
                    Infrastructure, InfrastructureImpl.
                    PLUGINS_FILENAME);
            }
        }

        public void BindData()
        {
            lblMessage.Visible = false;
            var data = Enumerable.Empty<dynamic>();

            try
            {
                data = XElement.Load(FilePath).Elements("plugin").Select(x => new
                {
                    Name = x.Attribute("name").Value,
                    Enabled = x.Attribute("enabled").Value.ParseAs(false)
                });
            }
            catch(Exception ex)
            {
                lblMessage.Visible = true;
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = ex.Message;
            }

            gvPlugins.DataSource = data;
            gvPlugins.DataBind();
        }

        protected void OnCommand(object sender, CommandEventArgs e)
        {
            lblMessage.Visible = false;
            lblMessage.Text = String.Empty;

            switch(e.CommandName)
            {
                case "Save":
                    {
                        var rows = gvPlugins.Rows;
                        if(rows.Count == 0)
                            return;

                        var xPlugins = new XElement("plugins");
                        foreach(GridViewRow i in rows)
                        {
                            var hdnName = i.FindControl("hdnName") as HiddenField;
                            var cbEnabled = i.FindControl("cbEnabled") as CheckBox;

                            xPlugins.Add(new XElement("plugin",
                                new XAttribute("name", hdnName.Value),
                                new XAttribute("enabled", cbEnabled.Checked)));
                        }
                        xPlugins.Save(FilePath);

                        lblMessage.ForeColor = Color.Green;
                        lblMessage.Text = "Operation completed successfully.";
                        lblMessage.Visible = true;
                    }
                    break;
            }
        }
    }
}